import { createStore } from "vuex";
import http from "../api/request";
import { initWebSocket } from "@/api/websocket"; // 引入封装好的 axios 实例

const store = createStore({
    state: {
        token: localStorage.getItem("token") || "", // 存储 token
        /*userInfo: {}, // 存储用户信息*/
        userInfo: JSON.parse(localStorage.getItem("userInfo")) || {},
        publishedTasks:[],
        sentServiceRecords: JSON.parse(localStorage.getItem("sentServiceRecords")) || [],
        receivedServiceRecords: JSON.parse(localStorage.getItem("receivedServiceRecords")) || [],
        socialTasks:[],
        schoolTasks:[],
        homeRecommendTasks:[],
        homeGroupTasks:[],
        contactList:[],
        chatMessages:[],
    },
    mutations: {
        // 1.更新 token
        setToken(state, token) {
            state.token = token;
            localStorage.setItem("token", token); // 存储到本地
        },
        // 2.更新用户信息
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            localStorage.setItem("userInfo", JSON.stringify(userInfo));
        },
        // 3.清除登录状态
        clearAuth(state) {
            state.token = "";
            state.userInfo = {};
            state.sentServiceRecords = [];
            state.receivedServiceRecords = [];
            state.contactList = [];
            state.chatMessages = [];
            localStorage.removeItem("token");
            localStorage.removeItem("userInfo");
            localStorage.removeItem("sentServiceRecords");
            localStorage.removeItem("receivedServiceRecords");
            localStorage.removeItem("contactList");
            localStorage.removeItem("chatMessages");
        },
        // 4.更新发布的任务
        setUserPublishedTasks(state, task) {
            if (Array.isArray(task)) {
                // 如果传入的是数组，替换整个任务列表
                state.publishedTasks = task;
            } else {
                // 如果传入的是单个任务对象，追加到任务数组
                state.publishedTasks.push(task);
            }
        },
        // 5.更新社会专区的任务
        setSocialTasks(state, task) {
            if (Array.isArray(task)) {
                state.socialTasks = task;
            } else {
                state.socialTasks.push(task);
            }
        },
        // 6.更新学校专区的任务
        setSchoolTasks(state, task) {
            if (Array.isArray(task)) {
                state.schoolTasks = task;
            } else {
                state.schoolTasks.push(task);
            }
        },
        // 7.获取任务记录（发单者）
        setSentServiceRecords(state, record) {
            if (Array.isArray(record)) {
                state.sentServiceRecords = record;
                localStorage.setItem("sentServiceRecords", JSON.stringify(record));
            } else {
                state.sentServiceRecords.push(record);
                localStorage.setItem("sentServiceRecords", JSON.stringify(record));
            }
        },
        // 8.获取任务记录（接单者）
        setReceivedServiceRecords(state, record) {
            if (Array.isArray(record)) {
                state.receivedServiceRecords = record;
                localStorage.setItem("receivedServiceRecords", JSON.stringify(record));
            } else {
                state.receivedServiceRecords.push(record);
                localStorage.setItem("receivedServiceRecords", JSON.stringify(record));
            }
        },
        // 9.获取首页推荐任务
        setHomeRecommendTasks(state, record) {
            if (Array.isArray(record)) {
                state.homeRecommendTasks = record;
                /*localStorage.setItem("homeRecommendTasks", JSON.stringify(record));*/
            } else {
                state.homeRecommendTasks.push(record);
                /*localStorage.setItem("homeRecommendTasks", JSON.stringify(record));*/
            }
        },
        // 10.获取首页组队任务
        setHomeGroupTasks(state, record) {
            if (Array.isArray(record)) {
                state.homeGroupTasks = record;
               /* localStorage.setItem("homeGroupTasks", JSON.stringify(record));*/
            } else {
                state.homeGroupTasks.push(record);
               /* localStorage.setItem("homeGroupTasks", JSON.stringify(record));*/
            }
        },
        // 11.更新联系人列表
        setContactList(state, contact) {
            if (Array.isArray(contact)) {
                state.contactList = contact;
                /*localStorage.setItem("contactList", JSON.stringify(contact));*/
            } else {
                state.contactList.push(contact);
               /* localStorage.setItem("contactList", JSON.stringify(contact));*/
            }
        },
        // 12.更新聊天记录
        setChatMessages(state, chatMessages) {
            if (Array.isArray(chatMessages)) {
                state.contactList = chatMessages;
                /*localStorage.setItem("chatMessages", JSON.stringify(chatMessages));*/
            } else {
                state.contactList.push(chatMessages);
               /* localStorage.setItem("chatMessages", JSON.stringify(chatMessages));*/
            }
        },

    },
    actions: {
        // 1. 密码登录
        async login({ commit, state }, payload) {
            try {
                const response = await http.post("/api/login/byPassword", null, {
                    params: {
                        phoneNumber: payload.phoneNumber,
                        password: payload.password,
                    },
                });
                const data = response.data;
                if (data.code === 200) {
                    commit("setToken", data.data.token);
                    commit("setUserInfo", { ...state.userInfo, phoneNumber: payload.phoneNumber });
                    if (state.userInfo.phoneNumber) {
                        initWebSocket(payload.phoneNumber,(message) => {
                            console.log("收到消息:", message);
                        });
                    }
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("登录失败", error);
                return { success: false, message: "登录请求失败" };
            }
        },
        // 2. 发送验证码
        async sendMsg(_, phoneNumber) {
            try {
                const response = await http.post("/api/login/sendMsg", null, {
                    params: { phoneNumber},
                    withCredentials: true, // 确保请求携带 cookie
                });
                const data = response.data;
                if (data.code === 200) {

                    return { success: true, message: "验证码发送成功" };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("验证码发送失败", error);
                return { success: false, message: "发送请求失败" };
            }
        },
        // 3. 验证码登录
        async loginByMsg({ commit, state }, payload) {
            try {
                const response = await http.post("/api/login/byCode", null, {
                    params: {
                        phoneNumber: payload.phoneNumber,
                        code: payload.code,
                    },
                    withCredentials: true, // 确保请求携带 cookie
                });
                const data = response.data;
                if (data.code === 200) {
                    commit("setToken", data.data.token);
                    commit("setUserInfo", { ...state.userInfo, phoneNumber: payload.phoneNumber });
                    if (state.userInfo) {
                        initWebSocket(payload.phoneNumber,(message) => {
                            console.log("收到消息:", message);
                        });
                    }

                    return { success: true , data:data.data.isFirstLogin};
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("登录失败", error);
                return { success: false, message: "登录请求失败" };
            }
        },
        // 4. 完善个人信息
        async completeInfo({ commit, state }, formData) {
            try {
                const response = await http.post("/api/login/submit", formData);
                const data = response.data;
                if (data.code === 200) {
                    // 合并返回的数据与原有 userInfo 的数据
                    const updatedUserInfo = {
                        ...state.userInfo,
                        ...formData
                    };
                    commit("setUserInfo", updatedUserInfo);
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息更新失败", error);
                return { success: false, message: "更新请求失败" };
            }
        },
        // 5. 修改个人信息
        async changeInfo({ commit, state }, formData) {
            try {
                const response = await http.put("/api/userInfo/changePersonalInfo", formData

                );
                const data = response.data;

                if (data.code === 200) {
                    // 合并返回的数据与原有 userInfo 的数据
                    const updatedUserInfo = {
                        ...state.userInfo,
                        ...formData
                    };
                    commit("setUserInfo", updatedUserInfo);
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息更新失败", error);
                return { success: false, message: "更新请求失败" };
            }
        },
        // 6.上传个人头像
        async updateAvatar({ commit, state }, avatar) {
            try {
                const response = await http.post("/api/userInfo/upLoadAvatar", avatar, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                const data = response.data;
                if (data.code === 200) {
                    const newAvatarUrl = data.data; // 假设后端返回新的头像 URL
                    commit("setUserInfo", { ...state.userInfo, avatar: newAvatarUrl });
                    return { success: true, data: data.data }; // 返回新 URL 供前端使用
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("头像上传失败:", error);
                return { success: false, message: "头像上传请求失败" };
            }
        },
        // 7.上传个人简历
        async updateResume({ commit, state }, resume) {
            try {
                const response = await http.post("/api/userInfo/upLoadResume", resume, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                const data = response.data;
                if (data.code === 200) {
                    const newResume = data.data; // 假设后端返回新的头像 URL
                    commit("setUserInfo", { ...state.userInfo, resume: newResume });
                    return { success: true, data: data.data }; // 返回新 URL 供前端使用
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("附件上传失败:", error);
                return { success: false, message: "附件上传请求失败" };
            }
        },
        // 8.上传任务文件
        async updateTaskFile({ commit, state },taskFile) {
            try {
                const response = await http.post("/api/task/upLoadTaskAttachment", taskFile, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                const data = response.data;
                if (data.code === 200) {
                    return { success: true, data: data.data }; // 返回新 URL 供前端使用
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("附件上传失败:", error);
                return { success: false, message: "附件上传请求失败" };
            }
        },
        // 9.上传任务图片
        async updateTaskImage({ commit, state },taskImage) {
            console.log(11,taskImage)
            try {
                const response = await http.post("/api/task/upLoadTaskImg", taskImage, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                const data = response.data;
                if (data.code === 200) {
                    return { success: true, data: data.data }; // 返回新 URL 供前端使用
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("图片上传失败:", error);
                return { success: false, message: "图片上传请求失败" };
            }
        },
        // 10. 上传任务信息
        async updateTaskInfo({ commit }, serviceData) {
            try {
                const response = await http.post("/api/task/deliverTask", serviceData);
                const data = response.data;
                if (data.code === 200) {
                   /* commit("setSentServiceRecords", serviceData);*/
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息更新失败", error);
                return { success: false, message: "更新请求失败" };
            }
        },
        // 11. 获取社会专区任务信息
        async getSocialTaskInfo({ commit }, filters) {
            try {
                const response = await http.post("/api/task/getSocialTask", filters,

                );
                const data = response.data;
                console.log("筛选条件", filters)
                if (data.code === 200) {
                    commit("setSocialTasks", data.data); // 更新任务信息
                    console.log("返回的数据", data.data)
                    return { success: true , data: data.data};
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("任务获取失败", error);
                return { success: false, message: "获取请求失败" };
            }
        },
        // 12. 获取校园专区任务信息
        async getSchoolTaskInfo({ commit }, filters) {
            try {
                const response = await http.post("/api/task/getSchoolTask", filters,

                );
                const data = response.data;
                console.log("筛选条件", filters)
                if (data.code === 200) {
                    commit("setSchoolTasks", data.data); // 更新任务信息
                    console.log("返回的数据", data.data)
                    return { success: true , data: data.data};
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("任务获取失败", error);
                return { success: false, message: "获取请求失败" };
            }
        },
        // 13. 设置/修改密码
        async changePassword({ commit , state }, passwordChangeMsg) {
            try {
                const response = await http.put("/api/userInfo/changePassword", passwordChangeMsg,{
                    headers:{
                        "Content-Type":"application/json"
                    }
                    }
                );
                const data = response.data;
                if (data.code === 200) {
                    commit("setUserInfo", { ...state.userInfo || {}, password: passwordChangeMsg.password }); // 更新用户密码信息
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("密码修改失败", error);
                return { success: false, message: "密码修改请求失败" };
            }
        },
        // 14. 获取任务记录（发单者）
        async getTaskRecordBySender({ commit }) {
            try {
                const response = await http.post("/api/userInfo/getTaskRecordsBySender");
                const data = response.data;
                if (data.code === 200) {
                    commit("setSentServiceRecords", data.data); // 更新信息
                    return { success: true ,data: data.data };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 15. 获取任务记录（接单者）
        async getTaskRecordByReceiver({ commit }) {
            try {
                const response = await http.post("/api/userInfo/getTaskRecordsByReceiver",null,{
                    /*headers: {
                        "Content-Type": "application/json"
                    }*/
                });

                const data = response.data;
                if (data.code === 200) {
                    commit("setReceivedServiceRecords", data.data); // 更新信息
                    return { success: true ,data: data.data };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 16. 获取个人信息（登录成功便调用）
        async getPersonalInfo({ commit }) {
            try {
                const response = await http.post("/api/userInfo/getPersonalInfo",null,{});
                console.log('获取个人信息',response.data)
                const data = response.data;
                if (data.code === 200) {
                    const { personalInfo, ratio } = data.data; // 解构对象
                    const updatedUserInfo = {
                        ...personalInfo, // 提取 personalInfo 的内容
                        ratio            // 添加 ratio
                    };
                    commit("setUserInfo", updatedUserInfo); // 提交到 Vuex
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 17. 获取首页卡片个人信息（登录成功后便调用）
        async getUserInfoInCard({ commit, state }) {
            try {
                const response = await http.post("/api/userInfo/getUserInfoInCard",null,{});

                const data = response.data;
                if (data.code === 200) {
                    // 合并返回的数据与原有 userInfo 的数据
                    const updatedUserInfo = {
                        ...state.userInfo, // 保留现有的 userInfo 属性
                        ...data.data       // 覆盖或新增返回的属性
                    };
                    commit("setUserInfo", updatedUserInfo);
                    console.log('卡片000',data.data)
                    console.log('卡片111',state.userInfo);
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 18. 获取首页推荐任务
        async getHomeRecommendTasks({ commit }, isGroup) {
            try {
                const response = await http.post("/api/task/getTaskOnHome", null, {
                    params: {
                        isGroup: isGroup
                    }});
                const data = response.data;
                if (data.code === 200) {
                    commit("setHomeRecommendTasks", data.data); // 更新信息
                    return { success: true ,data: data.data };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 19. 获取首页组队任务
        async getHomeGroupTasks({ commit }, isGroup) {
            try {
                const response = await http.post("/api/task/getTaskOnHome", null, {
                    params: {
                        isGroup: isGroup
                    }});
                const data = response.data;
                if (data.code === 200) {
                    commit("setHomeGroupTasks", data.data); // 更新信息
                    return { success: true ,data: data.data };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 20. 点击聊一聊后上传任务id和发布者的手机号
        async uploadTaskIdForChat({ commit, state },payload) {
            try {
                const response = await http.post("/api/chat/addContactOrChangeLatestTask", null, {
                    params: {
                        taskId:payload.taskId.value,
                        phoneNumber :payload.phoneNumber.value
                    }});
                const data = response.data;
                if (data.code === 200) {
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息上传失败", error);
                return { success: false, message: "信息上传请求失败" };
            }
        },
        // 21. 获取联系人列表信息
        async getContactList({ commit },currentUserPhoneNumber) {
            try {
                const response = await http.post("/api/chat/getContactListWithTaskInfo", null, {
                    params: {
                        currentUserPhoneNumber:currentUserPhoneNumber
                    }});
                const data = response.data;
                if (data.code === 200) {
                    /*const { contactInfo, taskInfo } = data.data; // 解构对象
                    const updatedContactList = {
                        ...contactInfo,
                        ...taskInfo
                    };
                    commit("setContactList", updatedContactList); // 提交到 Vuex*/
                    commit("setContactList", data.data);

                    console.log('联系人index',data.data);
                    return { success: true ,data: data.data };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 22. 获取具体聊天内容
        async getChatMessages({ commit,state },payload) {
            try {
                const response = await http.post("/api/chat/ChatMessages", null, {
                    params: {
                        phoneNumber1: payload.phoneNumber1,
                        phoneNumber2: payload.phoneNumber2
                    }});
                const data = response.data;
                console.log('手机号1',payload.phoneNumber1)
                console.log('手机号2',payload.phoneNumber2)
                if (data.code === 200) {
                    commit("setChatMessages", data.data);
                    console.log('聊天记录index，后端返回',data.data);
                    return { success: true , data: data.data};
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 23. 发送消息
        async sendMessage({ commit,state },messageForm) {
            try {
                const response = await http.post("/api/chat/sendMessage", messageForm);
                const data = response.data;
                if (data.code === 200) {
                    /*commit("setChatMessages", data.data);*/
                    console.log('发送的聊天记录index',messageForm);
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("信息获取失败", error);
                return { success: false, message: "信息获取请求失败" };
            }
        },
        // 24. 退出登录
        async exitLogin({ commit, state }) {
            try {
                const response = await http.put("/api/userInfo/exitLogin",);
                const data = response.data;

                if (data.code === 200) {

                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                console.error("退出失败", error);
                return { success: false, message: "退出请求失败" };
            }
        },
        // 5. 修改个人信息
        async confirmReceiver({ commit, state }, payload) {
            try {
                console.log('index',payload.id)
                console.log('index',payload.toWhoPhoneNumber);
                const response = await http.put("/api/task/confirmReceiver", null, {
                    params: {
                        taskId: payload.id,
                        receiverPhoneNumber: payload.toWhoPhoneNumber
                    }});
                console.log('index',payload.id)
                console.log('index',payload.toWhoPhoneNumber);
                const data = response.data;

                if (data.code === 200) {
                    return { success: true };
                } else {
                    return { success: false, message: data.msg };
                }
            } catch (error) {
                return { success: false, message: "发起交易失败" };
            }
        },
    },
    getters: {
        getToken: (state) => state.token,
        getUserInfo: (state) => state.userInfo,
        getSentServiceRecords: (state) => state.sentServiceRecords,
        getReceivedServiceRecords: (state) => state.receivedServiceRecords,
        getContactList: (state) => state.contactList,
        getChatMessages: (state) => state.chatMessages,
    },
});

export default store;
